/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mindorks.placeholderview;

import com.alibaba.fastjson.JSONArray;
import com.mindorks.placeholderview.bean.ExpandableBean;
import com.mindorks.placeholderview.bean.ImageBean;
import ohos.app.Context;
import ohos.global.resource.Resource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Utils
 *
 * @since 2021-05-27
 */
public class Utils {
    /**
     * 加载资源文件
     *
     * @param context 上下文
     * @return 数据集合
     */
    public static List<ImageBean> loadImages(Context context) {
        List<ImageBean> imageBeanList = JSONArray.parseArray(
                loadJSONFromAsset(context, "resources/rawfile/images.json"), ImageBean.class);
        return imageBeanList;
    }

    private static String loadJSONFromAsset(Context context, String jsonFileName) {
        String json = null;
        try {
            Resource resource = context.getResourceManager().getRawFileEntry(jsonFileName).openRawFile();
            InputStreamReader inputStreamReader = new InputStreamReader(resource, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            json = bufferedReader.readLine();
        } catch (IOException e) {
            e.fillInStackTrace();
            return null;
        }
        return json;
    }

    /**
     * 加载资源文件
     *
     * @param context 上下文
     * @return 数据集合
     */
    public static List<ExpandableBean> loadFeedTestData(Context context) {
        String str = loadJSONFromAsset(context, "resources/rawfile/news.json");
        return JSONArray.parseArray(str, ExpandableBean.class);
    }
}
